package com.wxh.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @ClassName: OneDataSourceConfig
 * @Description: mysql数据源配置类，作为主库
 * @Author wxh
 * @Date: 2021/4/16 14:31
 * @Version V1.0.0
 * @Since 1.8
 */
@Configuration
@MapperScan(basePackages = "com.wxh.mysql", sqlSessionTemplateRef = "oneSqlSessionTemplate" )
public class OneDataSourceConfig {


    @Primary
    @Bean(name = "oneDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.one")
    public DataSource oneDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "oneSqlSessionFactory")
    public SqlSessionFactory opinionSqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mysql/Student.xml"));
        return bean.getObject();
    }

    @Primary
    @Bean(name = "oneTransactionManager")
    public DataSourceTransactionManager opinionTransactionManager(@Qualifier("oneDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "oneSqlSessionTemplate")
    public SqlSessionTemplate opinionSqlSessionTemplate(
            @Qualifier("oneSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
